<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>工资想过万，键盘要敲烂</title>
</head>

<body>
 
<script>
    let data = [
      { id: 2, pid: 1 },
      { id: 5, pid: 2 },
      { id: 3, pid: 1 },
      { id: 1, pid: 0 },
      { id: 4, pid: 2 },
      { id: 6, pid: 3 },
    ];
    function tranListToTreeData(list,pid){
      let arr=[]
      list.forEach((item)=>{
        if (item.pid===pid) {
          const children=tranListToTreeData(list,item.id)
          if (children.length) {
            item.children=children
          }
          arr.push(item)
        }
      })
      return arr
    }
    let res=tranListToTreeData(data,0)
    console.log(res);
</script>
</body>

</html>